<template>
  <FormView
    v-model="entity"
    :title="entity.id ? '修改借用单' : '新建借用单'"
    :toolbar-attrs="{
      buttons: [
        'back',
        {
          save: true,
          submit: hasBtn('submit'),
          withdraw: flowContext.canWithdraw,
          reject: flowContext.canReject,
          finish: hasBtn('finish')
        }
      ]
    }"
    :toolbar-listeners="{
      save: () => saveAndStart({ title: `${userName}的借用单${entity.caseid}`, variables: { days: entity.days } }),
      submit: submitAudit,
      finish: () => submitAudit(),
      withdraw: () => withdrawAudit(),
      reject: () => reject()
    }">
    <FormHolder ref="form" label-width="120px" :model="entity" :disabled="entity.status === '2'">
      <FormItemGroup block-title="基本信息">
        <FormInput v-model="entity.caseid" prop="caseid" label="借用单号" disabled />
        <FormInput v-model="entity.createBy" prop="createBy" label="借用处理人" disabled />
        <FormInput
          v-model="entity.borrowName"
          prop="borrowName"
          placeholder="请选择借用人"
          label="借用人"
          required
          readonly>
          <template #append>
            <slot name="append">
              <ElButton type="button" style="padding-right: 10px" @click="isShowUserPicker = true"> 选择 </ElButton>
            </slot>
          </template>
        </FormInput>
        <FormInput v-model="entity.deptFullname" :span="12" prop="deptFullname" label="借用单位" disabled />
        <FormInput v-model="entity.remandName" :span="12" prop="remandName" label="归还处理人" disabled />
        <FormDatePicker v-model="entity.realRemandTime" date-time label="实际归还时间" prop="realRemandTime" disabled />
        <FormDatePicker v-model="entity.borrowTime" date-time label="借出时间" prop="borrowTime" />
        <FormDatePicker
          v-model="entity.forecastRemandTime"
          date-time
          label="预计归还时间"
          prop="forecastRemandTime"
          required />
        <FormTextarea v-model="entity.explains" label="借用说明" prop="explains" rows="5" max-length="3000" />

        <ElCol :span="24">
          <FlexRow vertical-center style="padding: 10px">
            <FlexItem><span style="color: #f56c6c">*</span>借用明细-物品列表</FlexItem>
            <ElButton size="mini" type="primary" class="el-icon-circle-plus" @click="isPickerShow = true">
              添加</ElButton
            >
            <ElButton size="mini" type="primary" class="el-icon-delete" @click="deleteSelectCard"> 删除所选</ElButton>
          </FlexRow>
          <FormTable
            ref="formTable"
            v-model="entity.borrowList"
            prop="borrowList"
            required
            selection-width="60"
            placeholder="请选择物品"
            editable
            :show-summary="true"
            hide-label
            :handle-column="false"
            :columns="columns" />
        </ElCol>
      </FormItemGroup>
      <FormItemGroup :gutter="0" block-title="附件信息">
        <UploadPage
          v-if="entity.unid"
          ref="UploadPage"
          style="padding: 0"
          :unique-code="entity.unid"
          model="receive"
          classify="purchaseOrder" />
      </FormItemGroup>
    </FormHolder>
    <!-- 流程发送选择框 -->
    <FlowableHandleUserTable :visible.sync="visibleUser" :selection="true" :multiple="true" />
    <AssetCardTable
      :visible.sync="isPickerShow"
      :asset-card-id="entity.id"
      in-type="DEVICE"
      :in-status="1"
      :multiple="true"
      @confirm="onConfirm" />
    <!-- 选择用户 -->
    <UserPicker
      v-if="isShowUserPicker"
      :reserve-position-on-close="false"
      close-on-click-modal
      :visible.sync="isShowUserPicker"
      @confirm="onConfirmUser" />
  </FormView>
</template>

<script>
  import { addObj, edit, putObj, create, delLists } from '@/api/asset/borrow'
  import FlowableHandleUserTable from '@/module/process/components/FlowableHandleUserTable.vue'
  import flowForm from '@/vue/mixin/flow-form'

  export default {
    name: 'BorrowDialogForm',
    docType: 'WF_BORROW',
    relativeViewId: 'BorrowView',
    components: {
      FlowableHandleUserTable
    },
    mixins: [flowForm],
    data() {
      return {
        columns: [
          { label: '资产分类', prop: 'ctiName' },
          { label: '资产编码', prop: 'number' },
          { label: '资产名称', prop: 'name' },
          { label: '规格型号', prop: 'model' },
          { label: '计量单位', prop: 'unit' },
          { label: '金额', prop: 'amount' },
          { label: '备注', prop: 'remarks' }
        ],
        selectedRows: [],
        isPickerShow: false,
        entity: {
          id: '',
          deptId: '254',
          deptFullname: '广州海洋地质调查局',
          createBy: 'liyue',
          createId: '1187',
          createTime: '2023-04-25 18:27:02',
          updateBy: null,
          updateTime: null,
          unid: '01cd6174-6e13-40c6-8c41-b60556f80f3b',
          caseid: null,
          status: '0',
          type: '0',
          borrowId: null,
          borrowName: null,
          borrowOuid: null,
          borrowOufullname: null,
          borrowOuname: null,
          remandId: null,
          remandName: null,
          remandOuid: null,
          remandOufullname: null,
          remandOuname: null,
          borrowTime: '2023-04-25 18:27:02',
          forecastRemandTime: '2023-04-25 18:27:02',
          realRemandTime: null,
          explains: null,
          detailed: null,
          borrowList: [],
          dictOption: {
            userTreeList: []
          }
        },
        visibleUser: false,
        isShowUserPicker: false
      }
    },
    methods: {
      create,
      load: edit,
      save: addObj,
      update: putObj,
      onConfirm(rows) {
        if (!this.entity.borrowList?.length) {
          rows.forEach(row => {
            this.$set(row, 'id', null)
            this.entity.borrowList.push(row)
          })
        } else {
          rows.forEach(row => {
            this.$set(row, 'id', null)
            if (!this.entity.borrowList.find(value => value.assetCardId === row.assetCardId)) {
              this.entity.borrowList.push(row)
            }
          })
        }
      },
      deleteSelectCard() {
        this.selectedRows = this.$refs.formTable.selectedRows
        if (this.selectedRows.length === 0) {
          this.$message.warning('请选择所需要删除的物品列表')
          return
        }
        const deleteIds = this.selectedRows.filter(item => item.id > 0).map(item => item.id)
        this.$confirm(`是否确认删除"${this.selectedRows.length} "条明细数据？`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            if (deleteIds.length > 0) {
              delLists(deleteIds)
            }
            this.entity.borrowList = this.entity.borrowList.filter(value => !this.selectedRows.includes(value))
          })
          .then(data => {
            this.$message.success('删除成功')
          })
      },
      onConfirmUser(users) {
        const user = users[0]
        this.entity.borrowId = user.id
        this.entity.borrowName = user.name
        this.entity.borrowOuid = user.deptId
        this.entity.borrowOufullname = user.deptName
      }
    }
  }
</script>
